$(document).ready((function () {
    var progressBar, totalWidth, timeout, startTime, counter,
            getRefreshBtnHandler, blinkLimit, blinkTimer, blink, warningMsg,
            warned;

    timeout = 1200000;
    blinkLimit = 60000;
    startTime = (new Date()).getTime();
    blinkTimer = null;
    warned = false;

    counter = function () {
        var time, link;
        time = (new Date()).getTime() - startTime;
        if (!warned && ((timeout - time) <= 60000)) {
            warned = true;
            if (confirm(warningMsg)) {
                getRefreshBtnHandler()();
            }
        }
        if ((timeout - time) <= 0) {
            location = link = location.href.substring(0,
                    location.href.indexOf('/admin/') + 7);
            return;
        }
        if (((timeout - time) < blinkLimit) && (blinkTimer === null)) {
            blinkTimer = setInterval(blink, 200);
        }
        progressBar.style.width = Math.round((timeout - time) / timeout *
                totalWidth) + 'px';
    };

    blink = function () {
        progressBar.style.visibility =
                progressBar.style.visibility === 'hidden' ? 'visible' :
                'hidden';
    };

    getRefreshBtnHandler = function () {
        return function () {
            var link = location.href.substring(0,
                    location.href.indexOf('/admin/') + 7);
            jQuery.get(link, undefined, function (data, textstatus) {
                if (textstatus === 'success') {
                    startTime = (new Date()).getTime();
                    if (blinkTimer !== null) {
                        clearInterval(blinkTimer);
                        blinkTimer = null;
                        progressBar.style.visibility = 'visible';
                    }
                    warned = false;
                } else {
                    alert('failed :(');
                }
            });
            return false;
        };
    };

    return function () {
        var refreshBtn;
        warningMsg = $('#timerunout').get(0).innerHTML;
        refreshBtn = $('p.f-right a')[0];
        refreshBtn.onclick = getRefreshBtnHandler();
        progressBar = $('p.f-right span.countdown-border span')[0];
        totalWidth = progressBar.offsetWidth;
        setInterval(counter, 1000);
    };
}()));
